<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>封装原生Ajax</title>
	<style type="text/css">
		#ems{
			position: absolute;
			left: 50%;
			width: 400px;
			height: auto;
			margin-left: -200px;
			background: lightGreen;
			text-align: center;
			min-height: 50px;
			height: 500px;
			overflow-y: scroll;
			overflow-x: hidden;
		}
		#ems input{
			height: 25px;
			margin-top: 10px;
		}
		#list{
			background: lightBlue;
		}
		#list li{
			text-align: left;
		}
	</style>
	
</head>
<body>
<div id="ems">
	<div>
		<input type="text" id="code">
		<input type="button" value="查询" id="btn">
	</div>
	<div id="list">
	</div>
</div>
<script type="text/javascript">
	function ajax(data){    // data中的参数  data={dataType:"xml/json",type:"get/post",url"",asyn:"true/false",succes:function(){},filure:function(){}}

	//data:{username:123,password:456}
	//data = 'username=123&password=456'
		//第一步创建xhr对象
		var xhr =null;
		if(window.XMLHttpRequest){
			xhr = new XMLHttpRequest();
		}else{
			xhr = new ActiveXObject('Microsoft.XMLHTTP');
		}
		//第二步：准备发送的信息参数
		var type = data.type == 'get'?'get':'post';  //判断是否为post还是get
		var url = '';
		if(data.url){
 			if(type == 'get'){   //如果是get 添加参数
				url += "?" + data.data + "&_t="+new Date().getTime();  //处理get方式的缓存问题
			}
		}
		var flag = data.asyn == 'true'?'true':'false';  //判断是否为异步还是同步
		xhr.open(type,url,flag);

		//第三步：执行发送的动作
		if(type == 'get'){
			xhr.send(null);
		}else if(type == 'post'){    // 如果是post方式 需要传递参数
			xhr.setReqestHeader("Content-Type","application/x-www-form-urlencoded");  //负责编码转换
			xhr.send(data.data);
		}
		

		//第四步：指定回调函数
		xhr.onreadystatechange = function(){
			if(this.readyState == 4){
				if(this.status == 200){   
					if(typeof data.succes == 'function'){   //判断成功的时候
						var d = data.dataType == 'xml'?xhr.responseXML:xhr.responseText;
						data.success(d);
					}
				}else{    //失败的时候
					if(typeof data.failure == 'function'){
						data.failure();
					}

				}
			}
		}
	}



	window.onload = function(){
		var btn = document.getElementById('btn');
		btn.onclick = function(){
			var param = {
				url:"data.php",
				type:'get',
				dataType:'json',
				success:function(data){
					alert(data);
				}
			};
			ajax(param);
			
		}
	}
</script>
</body>
</html>